package com.dk.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.entity.TUser;
import com.dk.mapper.TUserMapper;
import com.dk.service.impl.TUserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealmConfig extends AuthorizingRealm {


    @Autowired
    private TUserMapper tUserMapper;

//    执行授权逻辑

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        System.out.println(857);
        //给访问的方法授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加权限字符串 Collection : 顶层父类 ,List : Collection的接口 , ArrayList : list的实现类
//        List<String> perms = new ArrayList<>();
//        perms.add("insert");

//        根据当前登录的用户查询权限
        TUser tUser = (TUser) SecurityUtils.getSubject().getPrincipal();
//        List<String> perms = menuService.selectPermsByPid(tbAdmin.getAid());
//        info.addStringPermissions(perms);
        return null;
    }


//    执行登录(认证)逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行登录(认证)逻辑");
//        获取token对象
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("tname",token.getUsername());
        String uname = token.getUsername();
        TUser tUser = tUserMapper.selectOne(queryWrapper);
        if (tUser == null){
            return null;
        }
        //第一个参数:登录成功后,用户存放到session中
        //第二个参数:数据库中的密码
//        第三个参数:用户的盐
        //第四个参数:登录后.用户的账号名
        return new SimpleAuthenticationInfo(tUser,tUser.getTpwd(), ByteSource.Util.bytes(tUser.getSalt()),tUser.getTname());
    }
}
